package com.chen.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.reggie.common.BaseContext;
import com.chen.reggie.common.R;
import com.chen.reggie.entity.User;
import com.chen.reggie.service.UserService;
import com.chen.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取验证码
     *
     * @return
     */
    @PostMapping("sendMsg")
    private R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
            log.info("code={}", code);

            session.setAttribute("phone", code);
            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");
    }

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("login")
    private R<User> login(@RequestBody Map userMap, HttpSession session) {
        //获取手机号
        String phone = userMap.get("phone").toString();
        //获取验证码
        String code = userMap.get("code").toString();
        //从session中获取保存的验证码
        Object codeSession = session.getAttribute("phone");
        //进行验证码的比对
        if (codeSession != null && code.equals(codeSession)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                //判断当前手机号是否为新用户，若是则自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setId(BaseContext.getCurrentId());
//                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }
    /**
     * 登出
     *
     */
    @PostMapping("loginout")
    private R<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出登录");
    }
}
